function loadExamScheduleData() {
    // 调用 API 获取考试安排数据
    $.ajax({
        url: "http://localhost:8080/exam/list", // 替换为你的API地址
        method: "GET",
        dataType: "json",
        contentType: "application/json",
        cache: false,
        success: function (response) {
            // 清空考试安排表格数据
            $("#exam-schedule-tbody").empty();

            // 遍历后端返回的考试安排数组
            $.each(response.data, function (index, schedule) {
                const statusButtonClass = schedule.status === "已完成" ? "btn-success" : "btn-danger";
                const statusButtonText = schedule.status === "已完成" ? "已完成" : "未完成";
                let scheduleRowHTML = `<tr>
                    <td>${schedule.id}</td>
                    <td>${schedule.name}</td>
                    <td>${schedule.date}</td>
                    <td>${schedule.address}</td>
                    <td>${schedule.start_time}</td>                
                    <td>${schedule.end_time}</td>
                   <td><button class="btn ${statusButtonClass} btn-status btn-status-toggle" data-schedule-id="${schedule.id}">${statusButtonText}</button></td>
                   <td>
                        <button class="btn btn-sm btn-primary btn-edit-schedule" data-schedule-id="${schedule.id}">编辑</button>
                        <button class="btn btn-sm btn-danger btn-delete-schedule" data-schedule-id="${schedule.id}">删除</button>
                    </td>
                </tr>`;

                // 将表格行添加到表格中
                $("#exam-schedule-tbody").append(scheduleRowHTML);
            });

        },
        error: function (error) {
            // 如果出现错误，弹出错误消息
            console.error("获取考试安排数据失败：", error);
        }
    });
}


function resetExamScheduleForm() {
    $("#exam-course-name").val("");
    $("#exam-date").val("");
    $("#exam-location").val("");
    $("#exam-start-time").val("");
    $("#exam-end-time").val("");
}

function initializeExamScheduleTable() {
    loadExamScheduleData();
console.log("显示了");
    // 添加考试安排
    $('#add-exam-schedule-modal').on('shown.bs.modal', function () {
        $("#add-exam-schedule-btn").off().click(function () {
            let examCourseName = $("#exam-course-name").val();
            let examDate = $("#exam-date").val();
            let examLocation = $("#exam-location").val();
            let examStartTime = $("#exam-start-time").val();
            let examEndTime = $("#exam-end-time").val();

            if (examCourseName === "" || examDate === "" || examLocation === "" || examStartTime === "" || examEndTime === "") {
                alert("输入不能为空！");
                return;
            }

            examStartTime = examStartTime + ":00";
            examEndTime = examEndTime + ":00";

            $.ajax({
                url: "http://localhost:8080/exam/add",
                method: "POST",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    "name": examCourseName,
                    "date": examDate,
                    "address": examLocation,
                    "start_time": examStartTime,
                    "end_time": examEndTime
                }),
                success: function (response) {
                    if (response.message === "ok") {
                        alert("考试安排添加成功！");
                        $('#add-exam-schedule-modal').modal('hide');
                        resetExamScheduleForm();
                        loadExamScheduleData();
                    } else {
                        alert("操作失败: " + response.message);
                        resetExamScheduleForm();
                    }
                },
                error: function (error) {
                    console.error("添加考试安排操作失败：", error);
                }
            });
        });
    });

    // 删除考试安排
    // 删除考试安排按钮事件处理程序
    $("#exam-schedule-tbody").on("click", ".btn-delete-schedule", function () {
        let scheduleId = $(this).data("schedule-id");

        // 确认是否要删除
        if (!confirm("确定要删除此考试安排吗？")) {
            return;
        }

        // 发送 AJAX 请求以删除考试安排
        $.ajax({
            url: `http://localhost:8080/exam/delete/${scheduleId}`,
            method: "DELETE",
            dataType: "json",
            contentType: "application/json",
            success: function (response) {
                if (response.message === "ok") {
                    alert("考试安排删除成功！");
                    loadExamScheduleData();
                } else {
                    alert("操作失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("考试安排删除操作失败：", error);
            }
        });
    });

    // 编辑考试安排
    $('#edit-exam-schedule-modal').on('shown.bs.modal', function () {
        $('#saveExamScheduleChangesBtn').off().click(function () {
            let examId = $("#edit-exam-schedule-id").val();
            let examCourseName = $("#edit-exam-course-name").val();
            let examDate = $("#edit-exam-date").val();
            let examLocation = $("#edit-exam-location").val();
            let examStartTime = $("#edit-exam-start-time").val();
            let examEndTime = $("#edit-exam-end-time").val();

            if (examCourseName === "" || examDate === "" || examLocation === "" || examStartTime === "" || examEndTime === "") {
                alert("输入不能为空！");
                return;
            }

            examStartTime = examStartTime + ":00";
            examEndTime = examEndTime + ":00";

            $.ajax({
                url: "http://localhost:8080/exam/edit/" + examId,
                method: "PUT",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    "name": examCourseName,
                    "date": examDate,
                    "address": examLocation,
                    "start_time": examStartTime,
                    "end_time": examEndTime
                }),
                success: function (response) {
                    if (response.message === "ok") {
                        alert("考试安排更新成功！");
                        $('#edit-exam-schedule-modal').modal('hide');
                        loadExamScheduleData();
                    } else {
                        alert("操作失败: " + response.message);
                    }
                },
                error: function (error) {
                    console.error("编辑考试安排操作失败：", error);
                }
            });
        });
    });

// Display the edit exam schedule modal with data pre-filled
    $("#exam-schedule-tbody").on("click", ".btn-edit-schedule", function () {
        let scheduleRow = $(this).parent().parent();
        let examId = scheduleRow.children().eq(0).text();
        let courseName = scheduleRow.children().eq(1).text();
        let examDate = scheduleRow.children().eq(2).text();
        let location = scheduleRow.children().eq(3).text();
        let startTime = scheduleRow.children().eq(4).text().substring(0, 5);
        let endTime = scheduleRow.children().eq(5).text().substring(0, 5);

        $('#edit-exam-schedule-id').val(examId);
        $('#edit-exam-course-name').val(courseName);
        $('#edit-exam-date').val(examDate);
        $('#edit-exam-location').val(location);
        $('#edit-exam-start-time').val(startTime);
        $('#edit-exam-end-time').val(endTime);

        $('#edit-exam-schedule-modal').modal('show');
    });
// 考试安排状态按钮事件处理程序
    $("#exam-schedule-tbody").on("click", ".btn-status-toggle", function () {
        const statusButton = $(this);
        const scheduleId = statusButton.data("schedule-id");
        const currentStatus = statusButton.text();
        console.log(scheduleId);
        let newStatus;
        if (currentStatus === "未完成") {
            newStatus = "已完成";
        } else {
            newStatus = "未完成";
        }

        // 更新考试安排状态
        $.ajax({
            url: `http://localhost:8080/exam/updateStatus/${scheduleId}`, // 替换为你的API地址
            method: "PATCH",
            dataType: "json",
            data: JSON.stringify({status: newStatus}),
            contentType: "application/json",
            success: function (response) {
                const updatedStatus = response.data.status;
console.log(updatedStatus)
                if (updatedStatus === "已完成") {
                    alert("该考试完成！");
                    statusButton.text("已完成");
                    statusButton.removeClass("btn-danger");
                    statusButton.addClass("btn-success");
                } else {
                    statusButton.text("未完成");
                    statusButton.removeClass("btn-success");
                    statusButton.addClass("btn-danger");
                }
            },
            error: function (error) {
                console.error("更新考试状态失败：", error);
                alert("更新考试状态失败");
            }
        });
    });

}

function bindExamScheduleTableEvents(){
    initializeExamScheduleTable();
}



